import * as THREE from 'three'
import createApp from '../../core'

function createIcosahedronGeometry (dom: HTMLElement) {
  const { camera, scene, update, gui } = createApp(dom)
  camera.position.set(0, 0, 100)
  camera.lookAt(scene.position)

  const mesh = createIcosahedronFromGeometry()
  mesh.position.set(-40, 0, 0)
  scene.add(mesh)

  const bufferMesh = createIcosahedronFromBufferGeometry()
  bufferMesh.position.set(40, 0, 0)
  scene.add(bufferMesh)

  update((time: number) => {
    const angle = time / 2000
    mesh.rotation.set(angle, angle, 0)
    bufferMesh.rotation.set(angle, angle, 0)
  })

  function updateMeshs () {
    generateGeometry(mesh)
    generateGeometry(bufferMesh)
  }

  gui.add(data, 'radius', 0, 30).onChange(updateMeshs)
  gui.add(data, 'detail', 0, 10, 1).onChange(updateMeshs)
}

const data = {
  radius: 20,
  detail: 0
}

function createIcosahedronFromGeometry () {
  const { radius, detail } = data
  const geometry = new THREE.IcosahedronGeometry(radius, detail)
  const material = new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: true })
  const mesh = new THREE.Mesh(geometry, material)
  return mesh
}

function createIcosahedronFromBufferGeometry () {
  const { radius, detail } = data
  const geometry = new THREE.IcosahedronBufferGeometry(radius, detail)
  const material = new THREE.MeshNormalMaterial()
  const mesh = new THREE.Mesh(geometry, material)
  return mesh
}

function generateGeometry (mesh: THREE.Mesh) {
  const { radius, detail } = data
  const geometry = new THREE.IcosahedronBufferGeometry(radius, detail)
  mesh.geometry.dispose()
  mesh.geometry = geometry
}

export {
  createIcosahedronGeometry
}
